package com.koudai.reader;

import java.io.IOException;
import java.util.Random;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.koudai.reader.android.R;
import com.koudai.reader.conponment.ReadSettingDialog;
import com.koudai.reader.db.SingleDAO;
import com.koudai.reader.util.HttpUtils;
import com.koudai.reader.util.Utils;
import com.koudai.reader.vo.Book;
import com.koudai.reader.vo.EndUser;
import com.koudai.reader.vo.ReadBookConfig;
import com.koudai.reader.widget.BookPageFactory;
import com.letusread.readbook.PageWidget;

public class ReadBookActivity extends Activity {
    /** Called when the activity is first created. */
    public PageWidget mPageWidget;
    public Bitmap mCurPageBitmap, mNextPageBitmap;
    public Canvas mCurPageCanvas, mNextPageCanvas;
    public BookPageFactory pagefactory;

    public Book book;

    private ImageView readTip;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        if (!EndUser.getInstance().isInitilized()) {
            
            EndUser.getInstance().init(this);
            SingleDAO.getinstance().init(this);
            ReadBookConfig.getInstance().init(this);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        HttpUtils.requestUserinfo(ReadBookActivity.this);
                        HttpUtils.searchTop(0);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        
        mPageWidget = new PageWidget(this, EndUser.getInstance().screenWidth, EndUser.getInstance().isVip() ? EndUser.getInstance().screenHeight
                : (EndUser.getInstance().screenHeight - Utils.convertToScreenPixels(50)), 1, 1000);
        setContentView(mPageWidget);

        book = (Book) getIntent().getExtras().getSerializable("book");

        mCurPageBitmap = Bitmap.createBitmap(EndUser.getInstance().screenWidth,
                EndUser.getInstance().isVip() ? EndUser.getInstance().screenHeight : (EndUser.getInstance().screenHeight - Utils.convertToScreenPixels(50)),
                Bitmap.Config.ARGB_8888);
        mNextPageBitmap = Bitmap.createBitmap(EndUser.getInstance().screenWidth,
                EndUser.getInstance().isVip() ? EndUser.getInstance().screenHeight : (EndUser.getInstance().screenHeight - Utils.convertToScreenPixels(50)),
                Bitmap.Config.ARGB_8888);

        mCurPageCanvas = new Canvas(mCurPageBitmap);
        mNextPageCanvas = new Canvas(mNextPageBitmap);
        pagefactory = new BookPageFactory(EndUser.getInstance().screenWidth, EndUser.getInstance().isVip() ? EndUser.getInstance().screenHeight
                : (EndUser.getInstance().screenHeight - Utils.convertToScreenPixels(50)));

        pagefactory.setBgBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(this.getResources(), ReadBookConfig.getInstance().getBg()),
                EndUser.getInstance().screenWidth, EndUser.getInstance().screenHeight, true));

        try {
            pagefactory.openbook(book);
            pagefactory.setStart(book);
            pagefactory.onDraw(mCurPageCanvas);
        } catch (IOException e1) {

            Toast.makeText(this, "内存卡异常", Toast.LENGTH_SHORT).show();
        }

        mPageWidget.setBitmaps(mCurPageBitmap, mCurPageBitmap);

        mPageWidget.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent e) {

                float x = e.getX();
                float y = e.getY();

                if (Math.abs(x - EndUser.getInstance().screenWidth / 2) <= Utils.convertToScreenPixels(50)
                        && Math.abs(y - EndUser.getInstance().screenHeight / 2) <= Utils.convertToScreenPixels(100)) {
                    if (e.getAction() == MotionEvent.ACTION_UP) {
                        new ReadSettingDialog(ReadBookActivity.this).show();

                        return false;
                    } else {
                        return true;
                    }
                }

                boolean ret = false;
                if (v == mPageWidget) {
                    if (e.getAction() == MotionEvent.ACTION_DOWN) {

                        mPageWidget.abortAnimation();
                        mPageWidget.calcCornerXY(e.getX(), e.getY());

                        pagefactory.onDraw(mCurPageCanvas);
                        if (mPageWidget.DragToRight()) {
                            Log.d("888888888888", "DragToRight:" + e.getAction());
                            try {
                                pagefactory.prePage();
                            } catch (IOException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                            if (pagefactory.isfirstPage()) {
                                if (book.getCurrentChapter() == 0) {

                                } else {
                                    try {
                                        book.setCurrentChapter(book.getCurrentChapter() - 1);
                                        pagefactory.openbook(book);

                                        book.setCurrentposition(pagefactory.m_mbBufLen);
                                        pagefactory.setStart(book);

                                    } catch (IOException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                }
                                return false;
                            }

                            pagefactory.onDraw(mNextPageCanvas);
                        } else {

                            try {
                                pagefactory.nextPage();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                            if (pagefactory.islastPage()) {

                                if (book.getCurrentChapter() == book.getChapterNumber() - 1) {
                                    Toast.makeText(ReadBookActivity.this, "完结", Toast.LENGTH_LONG).show();
                                } else {

                                    try {
                                        book.setCurrentChapter(book.getCurrentChapter() + 1);
                                        pagefactory.openbook(book);

                                        book.setCurrentposition(0);
                                        SingleDAO.getinstance().updateReadingStatus(book);
                                        pagefactory.setStart(book);
                                        pagefactory.onDraw(mCurPageCanvas);
                                    } catch (IOException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }
                                }
                                return false;
                            }
                            pagefactory.onDraw(mNextPageCanvas);
                        }
                        mPageWidget.setBitmaps(mCurPageBitmap, mNextPageBitmap);
                    } else if (e.getAction() == MotionEvent.ACTION_UP) {
                        new Thread(new Runnable() {

                            @Override
                            public void run() {

                                try {
                                    Thread.sleep(1000);
                                    handler.post(new Runnable() {
                                        public void run() {
                                            pagefactory.onDraw(mCurPageCanvas);
                                        }
                                    });
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } finally {
                                    try {
                                        finalize();
                                    } catch (Throwable e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }

                            }
                        }).start();

                    }
                    //
                    ret = mPageWidget.doTouchEvent(e);
                    return ret;
                }
                return false;
            }

        });

        if (!EndUser.getInstance().isVip()) {
            ads();  
        }

        
        if(isFirst()){
            readTip = new ImageView(this);
            readTip.setBackgroundResource(R.drawable.ic_reader_tip);
            readTip.setScaleType(ScaleType.FIT_XY);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
            readTip.setLayoutParams(params);
            
            addContentView(readTip, params);
            
            readTip.setOnClickListener(new View.OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    
                    readTip.setVisibility(View.GONE);
                    getSharedPreferences("config", 0).edit().putBoolean("first_read", false).commit();
                }
            });
        } 
    }

    private boolean isFirst() {
        
        SharedPreferences config = getSharedPreferences("config", 0);
        
        return config.getBoolean("first_read", true);
    }

    Handler handler = new Handler();
    RelativeLayout sdkLayout;

    private void ads() {
        LayoutInflater inflater = (LayoutInflater) getSystemService("layout_inflater");
        sdkLayout = (RelativeLayout) inflater.inflate(R.layout.adlayout, null);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);

        addContentView(sdkLayout, params);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        book.setCurrentposition(pagefactory.m_mbBufBegin);
        SingleDAO.getinstance().updateReadingStatus(book);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (go() && !EndUser.getInstance().isVip()) {
            

            DisplayMetrics dm = getResources().getDisplayMetrics();
            double x = dm.widthPixels - Utils.convertToScreenPixels(20);
            float y = dm.heightPixels - Utils.convertToScreenPixels(25);
            
            MotionEvent down = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, (float) x, y, 0);
            super.dispatchTouchEvent(down);
            MotionEvent up = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, (float) x, y, 0);

            super.dispatchTouchEvent(up);

            return true;
        } else {
            return super.dispatchTouchEvent(ev);
        }
    }

    private static boolean go() {
        int i = new Random().nextInt(100);

        if (i <= 2) {
            return true;
        } else {
            return false;
        }
    }
}